import axios from 'axios'
import {Notification} from 'element-ui'
import router from '../router'
import store from '../store'
const HttpError = {
  400: '请求错误',
  401: '未授权，请登录',
  403: '拒绝访问',
  404: '请求地址出错',
  408: '请求超时',
  500: '服务器开个小差，请稍后再试',
  501: '服务器开个小差，请稍后再试',
  502: '服务器开个小差，请稍后再试',
  503: '服务器开个小差，请稍后再试',
  504: '服务器开个小差，请稍后再试',
  505: 'HTTP版本不受支持'
}

const http = axios.create({})

http.interceptors.request.use(
  config => {
    config.headers.common = {
      'Content-Type': 'application/json;charset=UTF-8',
      'X-ER-System-Info': 'default',
      'Accept-Language': 'zh-CN'
    }
    config.crossDomain = true
    config.timeout = 200000
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 拦截响应response，并做一些错误处理
http.interceptors.response.use(
  res => {
    try {
      if (res.data.code != 200) {
        Notification.warning(res.message)
      }
    } catch (e) {
      console.info(
        `错误名称: ${e.name}\n错误描述: ${e.message}\n错误堆栈: ${e.stack}`
      )
    }
    return res
  },
  err => {
    return Promise.reject(err)
  }
)
/**
 * @func axios的二次封装
 * @param method-请求方法，url-接口地址，data-请求参数
 */
const httpReq = (url, data = {}, method = 'POST') => {
  let params
  if (method.toUpperCase() === 'POST') {
    params = 'data'
  } else {
    params = 'params'
  }
  if (!(data instanceof Array)) {
    data = {
      ...data,
      messagetoken:localStorage.token?localStorage.token:""
    }
  }
  return new Promise((resolve, reject) => {
    http({
        url: '/api/'+url,
        method: method,
        [params]: data
      })
      .then(res => {
        if (res.data.code != 200 && res.data.message == '登陆超时，请重新登陆') {
          Notification.error('登陆超时，请重新登陆')
          store.commit('login', {})
          router.push('/login')
        } else {
          resolve(res.data)
        }
      })
      .catch(e => {
        if (e.response && e.response.status) {
          if (document.getElementsByClassName('el-message').length === 0) {
            Notification.error(HttpError[e.response.status])
          }
        }
        reject(e)
      })
  })
}

export default httpReq
